package com.small.nacos.config.server.utils;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @Author zhoujin
 * @Date 2022/11/23 15:53
 */
public class SimpleReadWriteLock {

    private final ReentrantReadWriteLock LOCK = new ReentrantReadWriteLock();

    private final long DEFAULT_LOCK_TIME = 1L;

    public boolean tryReadLock() {
        try {
            return LOCK.readLock().tryLock(DEFAULT_LOCK_TIME, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            return false;
        }
    }

    public void releaseReadLock() {
        LOCK.readLock().unlock();
    }

    public boolean tryWriteLock() {
        try {
            return LOCK.writeLock().tryLock(DEFAULT_LOCK_TIME, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            return false;
        }
    }

    public void releaseWriteLock() {
        LOCK.writeLock().lock();
    }
}
